<?php

namespace qore_base\web;
use \qore\base\Application;
use \qore\base\Controller;

/**
 * @author Samuel Nogueira <samuel.nogueira.dev@gmail.com>
 */
class WebApplication extends Application {
	public $name;
	protected $_controller;
	
	/**
	 * @return \qore\base\Controller
	 */
	public function getController($route = null) {
		return $this->_controller ?: $this->_controller = PageController::i();
	}
	
	public function run() {
	}
	
	/**
	 * Handles uncaught PHP exceptions.
	 * This method is implemented as a PHP exception handler.
	 * The application will be terminated by this method.
	 * @param Exception $exception exception that is not caught
	 */
	public function handleException(\Exception $exception) {
		// disable error capturing to avoid recursive errors
		restore_error_handler();
		restore_exception_handler();
		
		$this->displayException($exception);

		try {
			$this->end(1);
		} catch(\Exception $e) {
			// use the most primitive way to log error
			$msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
			$msg .= $e->getTraceAsString()."\n";
			$msg .= "Previous exception:\n";
			$msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
			$msg .= $exception->getTraceAsString()."\n";
			$msg .= '$_SERVER='.var_export($_SERVER, true);
			error_log($msg);
			exit(1);
		}
	}

	/**
	 * Handles PHP execution errors such as warnings, notices.
	 * This method is implemented as a PHP error handler.
	 * The application will be terminated by this method.
	 *
	 * @param integer $code the level of the error raised
	 * @param string $message the error message
	 * @param string $file the filename that the error was raised in
	 * @param integer $line the line number the error was raised at
	 */
	public function handleError($code, $message, $file, $line) {
		throw new \ErrorException($message, 0, $code, $file, $line);
	}

	/**
	 * Displays the uncaught PHP exception.
	 * @param Exception $exception the uncaught exception
	 */
	public function displayException(\Exception $exception) {
		if (QORE_DEBUG) {
			?>
			<h1><?= get_class($exception) ?></h1>
			<p><?= $exception->getMessage() ?> (<?= $exception->getFile() ?>:<?= $exception->getLine() ?>)</p>
			<pre><?= $exception->getTraceAsString() ?></pre>
			<?php
		} else {
			?>
			<h1><?= get_class($exception) ?></h1>
			<p><?= $exception->getMessage() ?></p>
			<?php
		}
	}
	
}
